package tm.actions;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import tm.data.DaoFactory;
import tm.data.UsersDao;
import tm.dto.Roles;
import tm.dto.Users;
import tm.gui.LoginForm;
import tm.operations.UserOperations;

/**
 * @version 	1.0
 * @author
 */
public class LoginAction extends Action

{

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionMessages errors = new ActionMessages();
        ActionForward forward = new ActionForward(); // return value

        try {

        	LoginForm loginData = (LoginForm)form;
        	Users user = null;
        	UserOperations userOp = new UserOperations();
        	user = userOp.getUserCredentials(loginData.getUserId(), loginData.getUserPassword());      	

        	System.out.println("First Name: "+user.getFirstName());
        	System.out.println("Last Name: "+user.getLastName());
        	System.out.println("Position: "+user.getPositions().getPositionTitle());
        	System.out.println("Roles: ");
        	Iterator iter = user.getRoleses().iterator();
        	while(iter.hasNext()){
        		System.out.print(((Roles)iter.next()).getRoleName()+",");
        	}
        		
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        	errors.add("name", new ActionMessage("id"));
        }
        
        if (!errors.isEmpty()) {
            saveErrors(request, errors);

            // Forward control to the appropriate 'failure' URI (change name as desired)
            forward = mapping.findForward("failure");

        } else {

            // Forward control to the appropriate 'success' URI (change name as desired)
            forward = mapping.findForward("success");

        }

        // Finish with
        return (forward);

    }
}
